import { createRouter, createWebHistory } from 'vue-router';
import { isEmpty } from '@/utils/common';
import api from '@/apis';
import { ElMessage } from 'element-plus';


const routes = [
  { 
    path: '/',
    name: 'Home',
    component: () => import('@/views/home/index.vue'),
  },
  {
    path: '/detail',
    name: 'Detail',
    component: () => import('@/views/detail/index.vue'),
  },
  {
    path: '/finance/accounting/bill/list',
    name: 'list',
    component: () => import('@/views/finance/accounting/bill/list.vue'),

  },
  {
    path: '/finance/accounting/bill/orderList',
    name: 'orderList',
    component: () => import('@/views/finance/accounting/bill/orderList.vue'),
    
  },
  {
    path: '/finance/accounting/bill/feeList',
    name: 'feeList',
    component: () => import('@/views/finance/accounting/bill/feeList.vue'),
    
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

router.beforeEach((to, from, next) => {
  if (!isEmpty(to.query.u)) {
    api.user.accountCheck({
        u: to.query.u,
        systemKey: '1'
      })
      .then(function (res) {
        if(res.code&&res.data&&res.data.detail&&res.data.detail.accessToken){
          sessionStorage.setItem('accessToken', res.data.detail.accessToken) 
          next()
        }else{
          next(new Error('unauthorized'))
        }
      })
  } else if (isEmpty(sessionStorage.getItem('accessToken'))) {
    next(new Error('unauthorized'))
  } else {
    next()
  }
})


router.onError(error => {
  if (error.message === 'unauthorized') {
    ElMessage.error('登录失效！')
  }
})

export default router